package com.xiaocz.hblsubstitutedriving.activities.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.hedan.textdrawablelibrary.TextViewDrawable;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.hblsubstitutedriving.App;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.base.BaseActivity;
import com.xiaocz.hblsubstitutedriving.interfaces.BeRobbedUtils;
import com.xiaocz.hblsubstitutedriving.interfaces.RoundRefresh;
import com.xiaocz.hblsubstitutedriving.model.CloudOrder;
import com.xiaocz.hblsubstitutedriving.utils.Constants;

import java.io.IOException;
import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Time:2019/9/9
 * Created by xiaocz
 * Describe 云订单
 */
@Deprecated
public class CloudActivity extends BaseActivity implements RoundRefresh {

    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.tv_start_address)
    TextViewDrawable tvStartAddress;
    @BindView(R.id.tv_end_address)
    TextViewDrawable tvEndAddress;
    @BindView(R.id.tv_time)
    TextView tvTime;

    private CloudOrder cloudOrder;

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_clound;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        cloudOrder = (CloudOrder) getIntent().getSerializableExtra("cloudOrder");
        BeRobbedUtils.setBeRobbedRefresh(this);
        orderCountDownTimer = new OrderCountDownTimer(cloudOrder.getT() * 1000, 1000);
        orderCountDownTimer.start();
    }

    @Override
    protected void initData() {
        if (cloudOrder != null) {
            tvOrder.setText("实时订单");
            tvStartAddress.setText(cloudOrder.getChufaaddress());
            tvEndAddress.setText(cloudOrder.getMudiaddress());
            btnTakeOrder.setText(String.valueOf("距您" + cloudOrder.getDistance() + "米,预估代驾费" + cloudOrder.getMoney() + "元，接单"));
            orderNo = cloudOrder.getOrderNo();
        } else {
            finish();
        }
    }

    @BindView(R.id.btn_take_order)
    TextView btnTakeOrder;

    @OnClick({R.id.right_btn, R.id.btn_take_order})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.right_btn://右上
                if (orderNo != null) {
                    webOrderStop();
                }
                break;
            case R.id.btn_take_order://接单
                if (cloudOrder != null) {
                    webTakeOrders(cloudOrder.getOrderNo());
                }
                break;
        }
    }


    /**
     * 接单
     */
    private void webTakeOrders(final String orderNo) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/ReceiptYunOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, " 接单");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus() && rspModel.getData() != null) {
                            OrderCourseActivity.show(mContext, orderNo);
                            finish();
                        } else {
                            if (rspModel.getMessage().contains("抢")) {
                                App.getInstance().showMessage(rspModel.getMessage());
                                finish();
                            } else if (rspModel.getMessage().contains("到期") || rspModel.getMessage().contains("无")) {
                                dialogVip(rspModel.getMessage());
                            } else {
                                App.getInstance().showMessage(rspModel.getMessage());
                                finish();
                            }
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        finish();
                        break;
                }
            }
        });
    }

    /**
     * 司机状态
     */
    private void dialogVip(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setCancelable(false);
        builder.setMessage(message);
        builder.setNegativeButton("去充值", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                VipActivity.show(mContext);
                finish();
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        if (!CloudActivity.this.isFinishing())//xActivity即为本界面的Activity
        {
            builder.create().show();
        }
    }


    private String orderNo;

    /**
     * 拒绝订单
     */
    private void webOrderStop() {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/driverRefuseOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                e.printStackTrace();
                finish();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, " 拒绝订单");
                finish();
            }
        });
    }

    /**
     * 未接订单
     */
    private void webOrderWeiJie() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/driverWeiJieOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
                finish();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, " 未接订单");
                finish();
            }
        });
    }


    @Override
    public void onRoundRefresh(int type, String message) {
        if (type == 99) {
            //App.getInstance().showMessage("订单已被抢！");
        }
    }

    private OrderCountDownTimer orderCountDownTimer;

    public class OrderCountDownTimer extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        private OrderCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (tvTime != null) {
                tvTime.setText(String.format("（%ss)", millisUntilFinished / 1000L));
            }
        }

        @Override
        public void onFinish() {
            webOrderWeiJie();
        }
    }

    @Override
    protected void onDestroy() {
        if (orderCountDownTimer != null) {
            orderCountDownTimer.cancel();
        }
        super.onDestroy();
    }
}
